<?php

namespace common\models\system;

use yii\db\ActiveRecord;

/**
 * Desc 动态 Model
 * TrendsModel::findx('user')->where(['id' => 1])->one();
 */
class TrendsModel extends ActiveRecord {

    //状态-启用
    public static $table = '';
    
    /**
     * 初始化
     * **/
    public function __construct($table, $config = [])
    {
        self::$table = $table;
        parent::__construct($config);
    }

    /**
     * {@inheritdoc}
     */
    public static function tableName() {
        return self::$table;
    }
    
    
     /**
     * @param $table
     * @return object
     * @throws InvalidConfigException
     */
    public static function findx($table)
    {
        if (self::$table != $table) {
            self::$table = $table;
        }
        return \Yii::createObject(ActiveQuery::className(), [get_called_class(), ['from' => [static::tableName()]]]);
    }
    
    /**
     * @param $table
     * @param $condition
     * @return mixed
     * @throws InvalidConfigException
     */
    public static function findOnex($table, $condition)
    {
        return static::findByConditionx($table, $condition)->one();
    }
    
    /**
     * @param $table
     * @param $condition
     * @return mixed
     */
    public static function findAllx($table, $condition)
    {
        return static::findByConditionx($table, $condition)->all();
    }
    
     /**
     * @param $table
     * @param $condition
     * @return string
     */
    protected static function findByConditionx($table, $condition)
    {
        $query = static::findx($table);

        if (!ArrayHelper::isAssociative($condition)) {
            $primaryKey = static::primaryKey();
            if (!isset($primaryKey[0])) {
                return '';
            }
            $condition = [$primaryKey[0] => $condition];
        }

        return $query->andWhere($condition);
    }

}
